function [traces] = interp_traces(traces, time, span, taperfrac)
%smooth and interpolate traces
%josh crozier 2020

if mod(length(time),2) == 1
    time = time(1:end-1);
end

for tracein = 1:length(traces) % loop over traces
    Ts_raw = seconds(1/traces(tracein).sampleRate);
    
    window = tukeywin(traces(tracein).sampleCount,...
        taperfrac);
    
    %lowess smoothing seems to produce less artifacts than any type of
    %filtering (fir, iir, filter-filtfilt, etc)
    %Not removing low frequencies, as there is no way to do this without
    %distorting data around steps/impulses and inducing some artificial
    %ringing
    spancount = floor(seconds(span)/seconds(Ts_raw)/2)*2+1;
    traces(tracein).data = smooth(detrend(traces(tracein).data).*window,...
        spancount, 'lowess');
    
    time_raw = traces(tracein).startTime + ...
        (seconds(0):Ts_raw:Ts_raw*(traces(tracein).sampleCount-1))';
    traces(tracein).data = interp1(time_raw, traces(tracein).data,...
        time, 'linear', 0);
    clear time_raw
    traces(tracein).sampleCount = length(traces(tracein).data);
    traces(tracein).sampleRate = 1/seconds(time(2)-time(1));
end

end

